#coding=utf-8

import numpy as np
import os
import re
from matplotlib import pyplot as plt

IS_REPLACE = True #true 会覆盖已经生成的图像 #false 不会覆盖已经生成的图像

def getfigure(fname):
    with open(fname,"r") as f:
        datas = []
        w,h = 0,0
        for line in f.readlines():
            if re.match("[\-\d][\d\.\s^\:]*$",line):
                if len(line.split(" ")) < 2:
                    continue
                h+=1
                w = 0
                for num in line.split(" ")[0:-1]:
                    datas.append(eval(num))
                    w+=1
        datas = np.asarray(datas).reshape(h,w).transpose()
        plt.title("Simple Data Figure")
        plt.xlabel("X")
        plt.ylabel("Y")
        for i in range(len(datas)-1):
            plt.plot(datas[0],datas[i+1])
        #plt.show()
        fg = fname[0:-4]+'.jpg'
        if os.path.isfile(fg):
            if IS_REPLACE:
                os.remove(fg) #覆盖已经生成的图片
            else:
                return #不覆盖已经生成的
        plt.savefig(fg)
        os.chmod(fg,511)

files = os.listdir()
for fname in files:
    if (re.match(".*\.txt",fname)):
        dataOrigin = []
        try:
            getfigure(fname)
            print(f"{fname}解析成功！")
        except:
            print(f"{fname}解析失败！")
